package com.yzr.common.thread;

import java.util.concurrent.CountDownLatch;

/**
 * @description 以空间换时间
 * @author: yx-0173
 * @date: 2021-06-18 16:16
 **/
public class SpaceForTime {

    public static long COUNT = 1000000000L;

    private static class T {
        /**
         * 因为cpu从内存读取时会顺势带走周边的变量，
         * 因为cpu的缓存长度可以存储的字节为64bytes，
         * 所以不管怎样，x在一个cpu中都是独立的，
         * 所以不存在缓存同步机制，大大提升了效率
         */
        protected long p1, p2, p3, p4, p5, p6, p7;
        public long x = 0L;
        protected long p8, p9, p10, p11, p12, p13, p14;
    }

    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < COUNT; i++) {
                arr[0].x = i;
            }
            latch.countDown();
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < COUNT; i++) {
                arr[1].x = i;
            }
            latch.countDown();
        });

        final long start = System.nanoTime();
        thread1.start();
        thread2.start();
        latch.await();
        System.out.println((System.nanoTime() - start) / 1000000);

    }

}
